package com.yonyou.pmclouds.completedcollate.rmiimpl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.consts.BillTypeConst;
import com.yonyou.pmclouds.basecom.entity.PageObject;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.util.DateUtils;
import com.yonyou.pmclouds.completedcatalog.mapper.CompletedCatalogBVOMapper;
import com.yonyou.pmclouds.completedcatalog.rmiitf.CompletedCatalogQuery;
import com.yonyou.pmclouds.completedcollate.entity.*;
import com.yonyou.pmclouds.completedcollate.mapper.CompletedCollateBVOMapper;
import com.yonyou.pmclouds.completedcollate.mapper.CompletedCollateContentVOMapper;
import com.yonyou.pmclouds.completedcollate.mapper.CompletedCollateVOMapper;
import com.yonyou.pmclouds.completedcollate.rmiitf.CompletedCollateQuery;
import com.yonyou.pmclouds.constructionlog.entity.ConstructionLogRefVO;
import com.yonyou.pmclouds.constructionlog.entity.ConstructionLogVO;
import com.yonyou.pmclouds.constructionlog.rmiitf.ConstructionLogQuery;
import com.yonyou.pmclouds.inspectitem.rmiitf.InspectItemService;
import com.yonyou.pmclouds.processinspect.entity.ProcedureInspectVO;
import com.yonyou.pmclouds.processinspect.rmiitf.ProcedureInspectRemoteService;
import com.yonyou.pmclouds.project.entity.ProjectVO;
import com.yonyou.pmclouds.project.rmiitf.ProjectSimpleQuery;
import com.yonyou.pmclouds.team.entity.TeamMemberVO;
import com.yonyou.pmclouds.team.mapper.TeamMapper;
import com.yonyou.pmclouds.workquality.entity.WorkqualityVO;
import com.yonyou.pmclouds.workquality.service.rmiitf.WorkqualityQueryService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.*;

/**
 * 竣工资料整理数据查询
 *
 * @author yzx
 * @Date: 2018/5/23 15:32
 */
@Service(version = ApplicationConsts.APPLICATION_VERSION, interfaceClass = CompletedCollateQuery.class)
public class CompletedCollateQueryImpl implements CompletedCollateQuery {

    @Autowired
    private CompletedCollateVOMapper collateVOMapper;
    @Autowired
    private CompletedCollateBVOMapper collateBVOMapper;
    @Autowired
    private CompletedCollateContentVOMapper collateContentVOMapper;
    @Autowired
    private CompletedCatalogBVOMapper catalogBVOMapper;
    @Autowired
    private TeamMapper teamMapper;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private CompletedCatalogQuery catalogQuery;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ProcedureInspectRemoteService procedureInspectRemoteService;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ConstructionLogQuery constructionLogQuery;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ProjectSimpleQuery projectSimpleQuery;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private WorkqualityQueryService workqualityQueryService;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private InspectItemService inspectItemService;

    @Override
    public PageObject search(String[] pkProjects, String condition, Integer start, Integer size) throws BusinessException {
        String pkTenant = RuntimeEnvironment.getTenantId();
        // 将传入的页码转成对应数据开始行
        start = (start - 1) * size;
        List<CompletedCollateVO> collateVOList = new ArrayList<>();
        // 分解查询条件
        if (condition == null) {
            condition = "";
        }
        String[] conditions = condition.split(" ");
        int pageCount = collateVOMapper.pageCount(conditions, start, size, pkTenant, pkProjects);
        if (pageCount > 0) {
            collateVOList = collateVOMapper.querypagebyconditions(conditions, start, size, pkTenant, pkProjects);
        }
        // 收集需要的各种主键
        Set<String> projectPks = new HashSet<>();
        /*Set<String> collatePks = new HashSet<>();

        List<CompletedCollateVO> visualCollateVO = new ArrayList<>();
        for (CompletedCollateVO collateVO : collateVOList) {
            if(ArrayUtils.contains(pkProjects,collateVO.getPkProject())){
                visualCollateVO.add(collateVO);
                projectPks.add(collateVO.getPkProject());
                collatePks.add(collateVO.getPkCompletedCollate());
            }
        }*/

        for (CompletedCollateVO collateVO : collateVOList) {
            projectPks.add(collateVO.getPkProject());
        }

        // 获取项目信息
        Map<String, ProjectVO> projectVOMap = projectSimpleQuery.queryProjects(projectPks.toArray(new String[projectPks.size()]));
        // 填充表体数据
        for (CompletedCollateVO collateVO : collateVOList) {
            // 填充项目信息
            ProjectVO projectVO = projectVOMap.get(collateVO.getPkProject());
            if (projectVO != null) {
                collateVO.setProjectName(projectVO.getSname());
                collateVO.setManager(projectVO.getManager());
            }
        }
        return new PageObject(collateVOList.toArray(new CompletedCollateVO[collateVOList.size()]), pageCount, start);
    }

    @Override
    public CompletedCollateVO getById(String id) throws BusinessException {
        // 根据主键获取竣工资料整理主表数据
        CompletedCollateVO collateVO = collateVOMapper.queryByPrimaryKey(id);
        // 根据主表主键获取子表数据
        CompletedCollateBVO[] collateBVOS = collateBVOMapper.queryBVOsByPkCollate(id);
        collateVO.setCollateBVOS(collateBVOS);
        // 填充具体内容信息
        fillCompletedContent(collateBVOS);
        return collateVO;
    }

    @Override
    public List<CollatedSearchPageVO> getBillsInfo(CollatedSearchParamVO paramVO) throws BusinessException {
        List<CollatedSearchPageVO> searchPageVOS = null;
        // 根据单据类型不同获取对应的单据数据
        switch (paramVO.getBillType()) {
            case BillTypeConst.PROCEDUREINSPECT_BILLTYPE:
                searchPageVOS = searchProcedureinspectBills(paramVO);
                break;
            case BillTypeConst.CONSTRUCTIONLOG_BILLTYPE:
                searchPageVOS = searchConstructionlogBills(paramVO);
                break;
        }
        return searchPageVOS;
    }

    @Override
    public List<NamePkVO> getQuoteNameAndPk(String[] procedureinspectpks) throws BusinessException {
        List<NamePkVO> result = new ArrayList<>();
        // 工序报验集合
        List<ProcedureInspectVO> procedureInspectVOList = procedureInspectRemoteService.queryByProcedureInspectPks(procedureinspectpks);
        for (ProcedureInspectVO procedureInspectVO : procedureInspectVOList) {
            // 施工记录pks
            Set<String> constructPks = new HashSet<>();
            // 构造第一层结果集
            NamePkVO namePkVO = new NamePkVO();
            namePkVO.setName(procedureInspectVO.getProcedure_name());
            namePkVO.setPk(procedureInspectVO.getPk_process_inspect());
            namePkVO.setPkProcedure(procedureInspectVO.getPk_procedure());
            // 第二层准备
            String[] pks = procedureInspectVO.getPk_records();
            if (pks != null && pks.length > 0) {
                constructPks.addAll(Arrays.asList(pks));
            }
            // 根据施工记录Pks获取所有数据
            ConstructionLogRefVO[] constructionLogRefVOS = null;
            // 用map缓存，顺便取出所有的质量标准pks
            Map<String, List<ConstructionLogRefVO>> logRefMap = new HashMap<>();
            Set<String> inspectstandardPks = new HashSet<>();
            // 第二层
            List<NamePkVO> subNamePkVOList = new ArrayList<>();
            if (constructPks.size() > 0) {
                constructionLogRefVOS = constructionLogQuery.queryByIds(constructPks.toArray(new String[constructPks.size()]));
                if (constructionLogRefVOS != null && constructionLogRefVOS.length > 0) {
                    for (ConstructionLogRefVO logRefVO : constructionLogRefVOS) {
                        inspectstandardPks.add(logRefVO.getPk_inspectstandard());
                    }
                    // 根据标准pks获取标准内容
                    Map<String, WorkqualityVO> stringWorkqualityVOMap = workqualityQueryService.queryByIDs(inspectstandardPks.toArray(new String[inspectstandardPks.size()]));

                    for (ConstructionLogRefVO logRefVO : constructionLogRefVOS) {
                        NamePkVO subNamePkVO = new NamePkVO();
                        subNamePkVO.setPk(logRefVO.getPk_constructionlog());
                        subNamePkVO.setName(stringWorkqualityVOMap.get(logRefVO.getPk_inspectstandard()).getCheckname());
                        subNamePkVOList.add(subNamePkVO);
                    }
                }
            }
            namePkVO.setSubObjs(subNamePkVOList.toArray(new NamePkVO[subNamePkVOList.size()]));
            result.add(namePkVO);
        }
        return result;
    }

    /**
     * 获取施工日志单据数据
     *
     * @param paramVO
     * @return java.util.List<com.yonyou.pmclouds.completedcollate.entity.CollatedSearchPageVO>
     * @author yzx
     * @date 2018/5/26 12:02
     */
    private List<CollatedSearchPageVO> searchConstructionlogBills(CollatedSearchParamVO paramVO) throws BusinessException {
        // 结果集
        List<CollatedSearchPageVO> searchPageVOS = new ArrayList<>();
        Map<String, Object> params = new HashMap<>();
        // 查询参数设置
        setSearchParams(paramVO, params);

        List<ConstructionLogVO> constructionLogVOS = constructionLogQuery.queryVosByParams(params);
        // 收集所有施工记录pks
        Set<String> constructionLogPks = new HashSet<>();
        Set<String> inspectStandardPks = new HashSet<>();
        for (ConstructionLogVO constructionLogVO : constructionLogVOS) {
            constructionLogPks.add(constructionLogVO.getPk_constructionlog());
            inspectStandardPks.add(constructionLogVO.getPk_inspectstandard());
        }
        // 根据标准pks获取标准内容
        Map<String, WorkqualityVO> stringWorkqualityVOMap = workqualityQueryService.queryByIDs(inspectStandardPks.toArray(new String[inspectStandardPks.size()]));
        // 获取施工记录合格率
        Map<String, BigDecimal> stringDoubleMap = inspectItemService.queryPassRateOfConstructLog(constructionLogPks.toArray(new String[constructionLogPks.size()]));
        for (ConstructionLogVO constructionLogVO : constructionLogVOS) {
            CollatedSearchPageVO searchPageVO = new CollatedSearchPageVO();
            searchPageVO.setPkBill(constructionLogVO.getPk_constructionlog());
            searchPageVO.setBillType(constructionLogVO.getBill_type());
            searchPageVO.setCreator(constructionLogVO.getCreator());
            searchPageVO.setCreationtime(constructionLogVO.getCreationtime());
            searchPageVO.setPkProcedure(constructionLogVO.getPk_process());
            searchPageVO.setProcedureName(constructionLogVO.getProcess_name());
            searchPageVO.setInspectarea(constructionLogVO.getInspectarea());
            searchPageVO.setConstruction(constructionLogVO.getPk_constructionunit());
            if (stringDoubleMap.get(constructionLogVO.getPk_constructionlog()) != null) {
                searchPageVO.setResult(stringDoubleMap.get(constructionLogVO.getPk_constructionlog()) + "%");
            } else {
                searchPageVO.setResult("0.00%");
            }
            // 检查标准名称
            searchPageVO.setInspectStandardName(stringWorkqualityVOMap.get(constructionLogVO.getPk_inspectstandard()).getCheckname());
            searchPageVOS.add(searchPageVO);
        }
        return searchPageVOS;
    }

    /**
     * 获取工序报验单据数据
     *
     * @param paramVO
     * @return java.util.List<com.yonyou.pmclouds.completedcollate.entity.CollatedSearchPageVO>
     * @author yzx
     * @date 2018/5/26 12:03
     */
    private List<CollatedSearchPageVO> searchProcedureinspectBills(CollatedSearchParamVO paramVO) throws BusinessException {
        // 结果集
        List<CollatedSearchPageVO> searchPageVOS = new ArrayList<>();
        Map<String, Object> params = new HashMap<>();
        // 查询参数设置
        setSearchParams(paramVO, params);
        List<ProcedureInspectVO> procedureInspectVOList = procedureInspectRemoteService.queryVosByParams(params);
        for (ProcedureInspectVO procedureInspectVO : procedureInspectVOList) {
            // 施工记录pks
            Set<String> constructPks = new HashSet<>();
            String[] pks = procedureInspectVO.getPk_records();
            if (pks != null && pks.length > 0) {
                constructPks.addAll(Arrays.asList(pks));
            }
            if (constructPks.size() > 0) {
                ConstructionLogRefVO[] constructionLogRefVOS = constructionLogQuery.queryByIds(constructPks.toArray(new String[constructPks.size()]));
                if (constructionLogRefVOS != null && constructionLogRefVOS.length > 0) {
                    StringBuilder inspectarea = new StringBuilder();
                    for (int i = 0; i < constructionLogRefVOS.length; i++) {
                        inspectarea.append(constructionLogRefVOS[i].getInspectarea());
                        if (i != constructionLogRefVOS.length - 1) {
                            inspectarea.append(";");
                        }
                    }
                    procedureInspectVO.setInspectarea(inspectarea.toString());
                }
            }
        }

        for (ProcedureInspectVO procedureInspectVO : procedureInspectVOList) {

            CollatedSearchPageVO searchPageVO = new CollatedSearchPageVO();
            searchPageVO.setPkBill(procedureInspectVO.getPk_process_inspect());
            searchPageVO.setBillType(procedureInspectVO.getBill_type());
            searchPageVO.setInspectarea(procedureInspectVO.getInspectarea());
            searchPageVO.setShowName(procedureInspectVO.getProcedure_name() + "-");
            searchPageVO.setCreator(procedureInspectVO.getCreator());
            searchPageVO.setCreationtime(procedureInspectVO.getCreationtime());
            searchPageVO.setPkProcedure(procedureInspectVO.getPk_procedure());
            searchPageVO.setProcedureName(procedureInspectVO.getProcedure_name());
            searchPageVO.setAcceptor(procedureInspectVO.getAcceptor());
            // 1:待审核 2：通过 3：不通过
            switch (procedureInspectVO.getBillstatus()) {
                case 1:
                    searchPageVO.setResult(CollatedSearchPageVO.RESULT_NO_AUDIT);
                    break;
                case 2:
                    searchPageVO.setResult(CollatedSearchPageVO.RESULT_PASS);
                    break;
                case 3:
                    searchPageVO.setResult(CollatedSearchPageVO.RESULT_NO_PASS);
                    break;
                default:
                    break;
            }
            searchPageVOS.add(searchPageVO);
        }
        return searchPageVOS;
    }

    private void setSearchParams(CollatedSearchParamVO paramVO, Map<String, Object> params) {
        // TODO 数据库中没有租户
        //params.put(CollatedSearchParamVO.PK_TENANT, RuntimeEnvironment.getTenantId());
        params.put(CollatedSearchParamVO.PK_PROJECT, paramVO.getPkProject());
        params.put(CollatedSearchParamVO.BILL_TYPE, paramVO.getBillType());
        params.put(CollatedSearchParamVO.CREATOR, paramVO.getCreator());
        params.put(CollatedSearchParamVO.PK_PROCEDURE, paramVO.getPkProcedure());
        params.put(CollatedSearchParamVO.INSPECTAREA, paramVO.getInspectarea());
        // 开始和结束时间特殊处理
        if (paramVO.getStartTime() != null) {
            params.put(CollatedSearchParamVO.START_TIME, DateUtils.asDateBegin(paramVO.getStartTime()));
        }
        if (paramVO.getEndTime() != null) {
            params.put(CollatedSearchParamVO.END_TIME, DateUtils.asDateEnd(paramVO.getEndTime()));
        }
    }

    private void fillCompletedContent(CompletedCollateBVO[] catalogBVOS) {
        if (catalogBVOS == null || catalogBVOS.length == 0) {
            return;
        }
        // 为子表填充具体单据内容(为减少对数据库请求，一次性查出)
        Set<String> pkCatalogBs = new HashSet<>();
        Set<String> pkCollateBs = new HashSet<>();
        for (CompletedCollateBVO collateBVO : catalogBVOS) {
            pkCatalogBs.add(collateBVO.getPkCompletedCatalogB());
            pkCollateBs.add(collateBVO.getPkCompletedCollateB());
        }
        // 填充表体关联内容
        List<CompletedCollateContentVO> contentVOList = collateContentVOMapper.queryByPkCollateBs(pkCollateBs.toArray(new String[pkCollateBs.size()]));
        for (CompletedCollateBVO collateBVO : catalogBVOS) {
            List<CompletedCollateContentVO> contentVOS = new ArrayList<>();
            for (CompletedCollateContentVO contentVO : contentVOList) {
                if (collateBVO.getPkCompletedCollateB().equals(contentVO.getPkCompletedCollateB())) {
                    contentVOS.add(contentVO);
                }
                collateBVO.setContentVOS(contentVOS.toArray(new CompletedCollateContentVO[contentVOS.size()]));
            }
        }
    }

    public TeamMemberVO[] getMemberByProject(String projectId) throws BusinessException{
        return teamMapper.queryTeamByProject(projectId);
    }
}
